package com.li.onjava8.utils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * TimedAbort 不会保持任何打开的任务，除非已完成任务，但如果任务需要太长时间，它仍将终止该任务
 * （TimedAbort 有时被称为守护进程）
 */
public class TimedAbort {
    private volatile boolean restart = true;

    public TimedAbort(double t, String msg) {
        CompletableFuture.runAsync(() -> {
            while (restart) {
                restart = false;
                try {
                    TimeUnit.MILLISECONDS.sleep((int)(1000*t));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        System.out.println(msg);
        System.exit(0);
    }

    public TimedAbort(double t) {
        this(t, "TimedAbort" + t);
    }

    public void restart() {
        restart = true;
    }
}
